package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manage/managerpc/internal/svc"
	"manage/managerpc/managerpc"
	"manage/models/cache"
	"manage/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type RateListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRateListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RateListLogic {
	return &RateListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RateListLogic) RateList(in *managerpc.RateListRequest) (*managerpc.RateListResponse, error) {
	// todo: add your logic here and delete this line
	var rate []mysql.Rate
	key := fmt.Sprintf("manageHotList")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		mysql.DB.Debug().Limit(10).Order("hot desc").Find(&rate)
		marshal, _ := json.Marshal(rate)

		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &rate)
	}

	mysql.DB.Debug().Find(&rate)
	var rateList []*managerpc.RateList
	for _, m := range rate {
		list := managerpc.RateList{
			Rate:    m.RateId,
			UserId:  m.UserId,
			Context: m.Context,
		}
		rateList = append(rateList, &list)
	}
	return &managerpc.RateListResponse{
		List: rateList,
	}, nil
}
